package com.test.reference;

import java.lang.ref.SoftReference;
import java.lang.ref.WeakReference;
import java.util.ArrayList;
import java.util.List;

public class ReferenceDemo {

    public void testStrongReference(int size) {
        Byte[] buff = new Byte[1024 * 1024 * size];
        System.out.println("testStrongReference: " + buff.toString());
        System.gc();
    }

    public void testSoftReference(int size) {
        Byte[] buff = new Byte[1024 * 1024 * size];
        SoftReference<Byte[]> softReference = new SoftReference<>(buff);
        Byte[] byteData = softReference.get();
        System.out.println("testSoftReference: " + byteData);
    }

    public void testSoftReferenceLoop(int size) {
//        byte[] buff = null;
        List<SoftReference<Byte[]>> objectList = new ArrayList<>();

        for (int i = 0; i < 10; i++) {
            Byte[] buff = new Byte[1024 * 1024 * size];
            SoftReference<Byte[]> softReference = new SoftReference<>(buff);
            objectList.add(softReference);
        }

        System.gc();

        for (SoftReference<Byte[]> srData : objectList) {
            Byte[] byteData = srData.get();
            System.out.println("testSoftReferenceLoop: " + byteData);
        }
    }

    public void testWeakReferenceLoop(int size) {
        List<WeakReference<Byte[]>> objectList = new ArrayList<>();

        for (int i = 0; i < 10; i++) {
            Byte[] buff = new Byte[1024 * 1024 * size];
            WeakReference<Byte[]> weakReference = new WeakReference<>(buff);
            objectList.add(weakReference);
        }

        System.gc();

        for (WeakReference<Byte[]> srData : objectList) {
            Byte[] byteData = srData.get();
            System.out.println("testWeakReferenceLoop: " + byteData);
        }
    }
}
